<template>
	<e-popup :show="formPopupShow" @close="formPopupShow = false">
		<view class="app-components-layout-form-popup">
			<view class="e-p-t-28 e-p-b-28 text-center bg-white">
				<text class="e-font-32 fw-500">{{formData.form.title}}</text>
			</view>
			<scroll-view scroll-y="true" >
				<view class="app-components-layout-form-popup__body e-rela">
					
					<goods-layout-form
						ref="goodsLayoutFormRef"
						v-model:value="goodsFormAnswerList"
						:info="formData.form"
						:skuId="formData.subFormDto.skuId"
						:proId="formData.subFormDto.proId"
						:price="price"
						:number="number"
						:disabled="disabled"
						@priceChange="handlePriceChange"
					>
					</goods-layout-form>
				</view>
			</scroll-view>
			<view class="app-components-layout-form-popup__footer bg-white e-flex e-flex-between">
				<view class="fw-500">
					<text>{{ $t('common.totalPrice') }}{{ $t('common.:') }}</text>
					<text class="c-red">{{ global.unitEn }}{{ priceFormat((disabled ? formData.subFormDto.totalPrice : totalPrice) || 0, 2) }}</text>
				</view>
				<view class="app-components-layout-form-popup__btn bg-primary e-flex-xy-center" @click="handleEditGoodsForm" v-if="!disabled">
					<text class="c-white fw-500">{{ $t('order.提交') }}</text>
				</view>
			</view>
		</view>
		
	</e-popup>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { postSubmitLayoutForm } from '@/common/request/api';
import type { CardFormData } from '@/common/request/api';
import type { LayoutFormModelValue, GoodsLayoutFormInstance } from '@/typings';
import { useUser, useGlobal } from '@/common/stores';
import { storeToRefs } from 'pinia';
import { priceFormat, isString, isBoolean } from '@/common/utils';

const props = withDefaults(
	defineProps<{
		value: boolean;
		formData?: CardFormData;
		price: number;
		number: number;
		subType: 0 | 1 | 2 | false;
		disabled?: boolean;
	}>(),
	{}
);
const emit = defineEmits(['edit', 'updatePrice', 'update:value']);
const { global } = storeToRefs(useGlobal());

const formPopupShow = computed({
	get() {
		return props.value;
	},
	set(v) {
		emit('update:value', v);
	}
});
const goodsLayoutFormRef = ref<GoodsLayoutFormInstance>();

const goodsFormAnswerList = ref<LayoutFormModelValue>([]);

const totalPrice = ref(0)
const handlePriceChange = (e:number) => {
	totalPrice.value = e
}

watch(
	() => props.formData,
	(v) => {
		if (v) {
			goodsFormAnswerList.value = v.form.formOptions.map((item) => {
				const answer = v!.subFormDto.list.find((items) => items.formOptionsId === item.id);
				let formOptionsInfoId: undefined | string | string[] = undefined;
				let vle = answer?.vle;
				let formOptionsInfoIdText = answer?.formOptionsInfoIdText || ''; //有“其他”选项的题目，用于存储选择“其他”选项时输入框输入的内容
				if (answer && answer.formOptionsInfoId) {
					formOptionsInfoId = answer.formOptionsInfoId;
					if ([3, 4, 5].includes(item.type)) {
						// 3为单选、4为多选，5为下拉选择
						// 其中3、4有其他选项，formOptionsInfoId有可能为json数组
						// 2024/10/21 json数组形式已弃用，改为formOptionsInfoIdText存储
						// 但为兼容旧数据解析，保留此段代码
						if (formOptionsInfoId[0] === '[') {
							// 是json数组，则代表多选题或单选题中选择了‘其它’这个选项，此时这个数组第零位是答案列表，第一位是选择‘其它’这个选项时输入的内容
							const arr: string[] = JSON.parse(formOptionsInfoId);
							formOptionsInfoId = arr[0];
							formOptionsInfoIdText = arr[1];
						}
						vle = '';
					}

					formOptionsInfoId = item.type === 4 ? formOptionsInfoId.split(',') : formOptionsInfoId;
				}
				return {
					formOptionsId: item.id,
					formOptionsInfoId: formOptionsInfoId || ([4, 5].includes(item.type) ? [] : ''),
					formOptionsInfoIdText,
					vle: vle || '',
					fileList: item.type === 6 ? (vle ? JSON.parse(vle) : []) : undefined,
					vleid: item.vleid
				};
			});
			
		} else {
			goodsFormAnswerList.value = [];
		}
	},
	{
		immediate: true
	}
);

const handleEditGoodsForm = async () => {
	const res = await goodsLayoutFormRef.value?.validate?.();
	if (!res) {
		return;
	}

	handleSubmitGoodsForm(props.subType).then(() => {
		formPopupShow.value = false;
		emit('edit', goodsFormAnswerList.value);
	});
};

const handleSubmitGoodsForm = async (subType: 0 | 1 | 2 | false) => {
	const submitList = goodsFormAnswerList.value.map((item) => {
		let formOptionsInfoId = isString(item.formOptionsInfoId) ? item.formOptionsInfoId : item.formOptionsInfoId?.join?.(',') || '';
		return {
			formOptionsId: item.formOptionsId,
			formOptionsInfoIdText: item.formOptionsInfoIdText,
			formOptionsInfoId,
			vle: (item.fileList?.length ? JSON.stringify(item.fileList) : item.vle) || formOptionsInfoId
		};
	});
	if (isBoolean(subType)) {
		formPopupShow.value = false;
		emit('edit', submitList);
		return;
	}
	const res = await postSubmitLayoutForm({
		proId: props.formData!.subFormDto.proId,
		subType: subType,
		skuId: props.formData!.subFormDto.skuId,
		formId: props.formData!.formId,
		proPrice: props.price,
		proSize: props.number,
		list: submitList
	});

	emit('updatePrice', res.data.subFormDto.totalPrice);
};

defineExpose({
	submitGoodsForm: handleSubmitGoodsForm
});
</script>

<style lang="scss" scoped>
@include appBem_b(components-layout-form-popup) {
	background: #F8F8F8;
	scroll-view{
		height: 70vh;
	}
	@include appBem_e(btn) {
		min-width: 360rpx;
		height: 90rpx;
		border-radius: 2rpx;
		padding: 0 20rpx;
	}

	@include appBem_e(footer) {
		height: 110rpx;
		padding: 0 20rpx;
	}
}
</style>
